﻿@{
    ViewBag.Title = "ShopCartWatch";
    Layout = "~/Views/Shared/_Page.cshtml";
}

<style type="text/css">
    div {
        color: #99AA33;
    }
    .cartLabel {
        float: left;
        width: 100px;
        margin: 10px;
    }
    .cartValue {
        float: left;
        width: 400px;
        margin: 10px;
    }
</style>

<h2>Shopping Cart Watch</h2>

<div ng-app ng-controller="CartController">
    <div ng-repeat="item in items">
        <div class="cartLabel">{{item.title}}</div>
        <div class="cartValue">
            <input ng-model="item.quantity">
            <span>{{item.price | currency}}</span>
            <span>{{item.price * item.quantity | currency}}</span>
        </div>
        <div style="clear: both;"></div>
    </div>
    <div>Total: {{totalCart() | currency}}</div>
    <div>Discount: {{bill.discount | currency}}</div>
    <div>Subtotal: {{subtotal() | currency}}</div>
</div>

<script>
    function CartController($scope) {
        $scope.bill = {};

        $scope.items = [
            {title: 'Paint pots', quantity: 8, price: 3.95},
            {title: 'Polka dots', quantity: 17, price: 12.95},
            {title: 'Pebbles', quantity: 5, price: 6.95}
        ];
        
        $scope.totalCart = function() {
            var total = 0;
            for (var i = 0, len = $scope.items.length; i < len; i++) {
                total = total + $scope.items[i].price * $scope.items[i].quantity;
            }

            return total;
        };

        $scope.subtotal = function() {
            return $scope.totalCart() - $scope.bill.discount;
        };

        function calculateDiscount(newValue, oldValue, scope) {
            $scope.bill.discount = newValue > 100 ? 10 : 0;
        }
        
        $scope.$watch($scope.totalCart, calculateDiscount);
    }
</script>